package com.ma.chapter4.t8;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.LockSupport;

/**
 * @ClassName ByOrderOut3
 * @Author: mayongqiang
 * @DATE 2022/3/17 0:01
 * @Description: park() unpark() 实现交替输出
 */
@Slf4j(topic = "m.ByOrderOut3")
public class ByOrderOut3 {
    static Thread t1;
    static Thread t2;
    static Thread t3;

    public static void main(String[] args) {
        ParkUnpark parkUnpark = new ParkUnpark(5);
        t1 = new Thread(() -> {
            parkUnpark.print("a",t2);
        });
        t2 = new Thread(() -> {
            parkUnpark.print("b",t3);
        });
        t3 = new Thread(() -> {
            parkUnpark.print("c",t1);
        });
        t1.start();
        t2.start();
        t3.start();

        LockSupport.unpark(t1);

    }

}

class ParkUnpark {
    private int loopNumber;

    public ParkUnpark(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    public void print(String str, Thread next) {
        for (int i = 0; i < loopNumber; i++) {
            LockSupport.park();
            System.out.print(str);
            LockSupport.unpark(next);
        }
    }
}
